package com.concerneyes.mine.TabActivity.OrderView;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.concerneyes.CEApp;
import com.concerneyes.R;
import com.concerneyes.health.Task.GlassManDataImpl;
import com.concerneyes.health.Task.GlassManDataListener;
import com.concerneyes.health.adapter.HealthAdapter;
import com.concerneyes.health.model.HealthDataModel;
import com.concerneyes.mine.Task.AdressImpl;
import com.concerneyes.mine.Task.AdressListener;
import com.concerneyes.mine.model.MyAdressModel;
import com.concerneyes.mine.model.OrderListModel;
import com.concerneyes.pay.ConfirmInfoActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import common.AbsActivity;
import common.PreferUtil;
import http.HttpAsyncTask;
import http.JsonMap;
import http.Url;
import util.ActivityUtil;
import util.ImageUtil;
import util.ToastHelper;
import util.Util;
import view.ListViewForScrollView;

/**
 * 我的订单详情
 */

public class MyOrderDetail extends AbsActivity implements View.OnClickListener, AdressListener {
    private static final int WAN_SHAN = 101;
    private static final int QUIT_RENT = 102;
    private ScrollView sl_order_detail;
    private LinearLayout ll_data;
    //提醒部分
    private ImageView mIvGone;
    private FrameLayout mFlEditInfo;
    //订单详情部分
    private TextView mOrderStyle;
    private TextView mOrderNum;
    private TextView mOrderTime;
    private TextView mLookLog;
    //商品部分
    private ImageView mIvGoods;
    private TextView mTvItemtitle;
    private TextView mTvGoodsParam;
    private TextView mTvGoodsParam1;
    private TextView mTvGoodsPrice;
    private TextView mTvGoodsNum;
    private TextView mLogMoney;
    //收货信息部分
    private TextView mAdressName;
    private TextView mTvAdressName;
    private TextView mTvAdressPhone;
    private TextView mTvAdressDetail;
    private TextView mLeaveMsg;
    private RelativeLayout mRlLeaveMsg;
    private LinearLayout mLlAdressMsg;
    //配镜信息部分
    private TextView mGlassName;
    private TextView mOptometryDate;
    private TextView mDataCome;
    private LinearLayout mLlGlassMsg;
    private ListViewForScrollView mLvOptometry;
    private HealthAdapter adapter;
    /**
     * 物流单号
     */
    private TextView mBtnLeft;
    /**
     * 物流单号
     */
    private TextView mBtnRight;
    private LinearLayout mllBottomBtn;
    private int order_style;
    private AdressImpl adressImpl;
    private int addressId;
    private RelativeLayout rlLookLog;
    private OrderListModel models = null;
    private LinearLayout ll_loading;
    private String orderId;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_order_detail);
        setTitle(R.string.order_detail);
        orderId = getIntent().getExtras().getString("orderId");
        initView();
    }

    private void initView() {
        mLvOptometry = (ListViewForScrollView) findViewById(R.id.lv_optometry);
        ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
        sl_order_detail = (ScrollView) findViewById(R.id.sl_order_detail);
        ll_data = (LinearLayout) findViewById(R.id.ll_data);
        adapter = new HealthAdapter(this, null, false, true);
        mLvOptometry.setAdapter(adapter);
        sl_order_detail.smoothScrollTo(0, 0);
        ll_data.setBackground(getResources().getDrawable(R.drawable.btn_gray_bold_bg));
        mIvGone = (ImageView) findViewById(R.id.iv_gone);
        mFlEditInfo = (FrameLayout) findViewById(R.id.fl_edit_info);

        mOrderStyle = (TextView) findViewById(R.id.order_style);
        mOrderNum = (TextView) findViewById(R.id.order_num);
        mOrderTime = (TextView) findViewById(R.id.order_time);
        mLookLog = (TextView) findViewById(R.id.look_log);

        mIvGoods = (ImageView) findViewById(R.id.ivGoods);
        mTvItemtitle = (TextView) findViewById(R.id.tvItemtitle);
        mTvGoodsParam = (TextView) findViewById(R.id.tvGoodsParam);
        mTvGoodsParam1 = (TextView) findViewById(R.id.tvGoodsParam1);
        mTvGoodsPrice = (TextView) findViewById(R.id.tvGoodsPrice);
        mTvGoodsNum = (TextView) findViewById(R.id.tvGoodsNum);
        mLogMoney = (TextView) findViewById(R.id.log_money);
        mAdressName = (TextView) findViewById(R.id.adress_name);
        mTvAdressName = (TextView) findViewById(R.id.tv_adress_name);
        mTvAdressPhone = (TextView) findViewById(R.id.tv_adress_phone);
        mTvAdressDetail = (TextView) findViewById(R.id.tv_adress_detail);
        mLeaveMsg = (TextView) findViewById(R.id.leave_msg);
        mRlLeaveMsg = (RelativeLayout) findViewById(R.id.rl_leave_msg);
        mLlAdressMsg = (LinearLayout) findViewById(R.id.ll_adress_msg);
        mGlassName = (TextView) findViewById(R.id.glass_name);
        mOptometryDate = (TextView) findViewById(R.id.optometry_date);
        mDataCome = (TextView) findViewById(R.id.data_come);
        mLlGlassMsg = (LinearLayout) findViewById(R.id.ll_glass_msg);
        mBtnLeft = (TextView) findViewById(R.id.btn_left);
        mBtnRight = (TextView) findViewById(R.id.btn_right);
        mllBottomBtn = (LinearLayout) findViewById(R.id.ll_bottom_btn);
        rlLookLog = (RelativeLayout) findViewById(R.id.rl_look_log);
        mBtnLeft.setOnClickListener(this);
        mBtnRight.setOnClickListener(this);
        mLookLog.setOnClickListener(this);
        mIvGone.setOnClickListener(this);
        adressImpl = new AdressImpl(this, this);
        orderDetail();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_gone:
                mFlEditInfo.setVisibility(View.GONE);
                break;
            case R.id.look_log:
                break;
            case R.id.btn_left:
                Bundle bundle = new Bundle();
                bundle.putString("OrderId", orderId);
                ActivityUtil.setIntentForResult(this, QuitRentActivity.class, bundle, QUIT_RENT);
                break;
            case R.id.btn_right:
                if (order_style == 0) {
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("orderId", orderId);
                    ActivityUtil.setIntentForResult(this, ConfirmInfoActivity.class, bundle1, WAN_SHAN);
                } else if (order_style == 2) {
                    confirmGoods();
                }
                break;
            case R.id.rl_look_log:
                String expressNo = models.getExpressNo();
                Bundle bundle1 = new Bundle();
                bundle1.putString("title", getResources().getString(R.string.log_mag));
                if (!TextUtils.isEmpty(expressNo)) {
                    bundle1.putString("url", Url.BaseUrl + "/kuaidi/search?nu=" + expressNo);
                } else {
                    bundle1.putString("url", Url.BaseUrl + "/kuaidi/search?nu=59655403387");
                }
                ActivityUtil.setIntent(this, CheckLogActivity.class, bundle1);
                break;
        }
    }

    private void confirmGoods() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uid", PreferUtil.getUserId());
        params.put("id", orderId);
        HttpAsyncTask http = new HttpAsyncTask() {
            @Override
            public void onStart(String taskId) {
            }

            @Override
            public void onFinish(String taskId, String response) {
                JsonMap ret = JsonMap.parseJson(response);
                if (ret == null) {
                    Toast.makeText(MyOrderDetail.this, R.string.network_error_tip, Toast.LENGTH_SHORT).show();
                    return;
                }
                if (ret.getInt("code") == 200) {
                    Toast.makeText(MyOrderDetail.this, ret.getString("msg"), Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(MyOrderDetail.this, ret.getString("msg"), Toast.LENGTH_SHORT).show();
                }
            }
        };
        http.setDebug(true);
        http.excute(Url.BaseUrl + "/order/confirm", params, "POST");
    }

    /**
     * 订单详情
     */
    public void orderDetail() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uid", PreferUtil.getUserId());
        params.put("id", orderId);
        HttpAsyncTask http = new HttpAsyncTask() {
            @Override
            public void onStart(String taskId) {
                showLoadingDialog(R.string.loading);
            }

            @Override
            public void onFinish(String taskId, String response) {
                cancelLoadingDialog();
                JsonMap ret = JsonMap.parseJson(response);
                if (ret == null) {
                    ToastHelper.getInstance()._toast(R.string.network_error_tip);
                    return;
                }
                OrderListModel model = null;
                if (ret.getInt("code") == 200) {
                    String datas = ret.getMap("data").toString();
                    try {
                        model = new Gson().fromJson(datas, OrderListModel.class);
                    } catch (Exception e) {
                    }
                    if (model == null) {
                        // 暂无数据
                        return;
                    }
                    setOrderData(model);
                } else {
                    ToastHelper.getInstance()._toast(ret.getString("msg"));
                }
            }
        };
        http.setDebug(true);
        http.excute(Url.BaseUrl + "/order/details", params, "POST");
    }
    private void setOrderData(OrderListModel data) {
        order_style = data.getStatus() - 1;
        ll_loading.setVisibility(View.GONE);
        this.models = data;
        Log.e(this.getClass().getSimpleName(), "data==>>>" + data.toString());
        String[] orderStyle = getResources().getStringArray(R.array.order_me_style2);
        mOrderStyle.setText(orderStyle[order_style]);
        if (data.getStatus() == 1) {
            mFlEditInfo.setVisibility(View.VISIBLE);
            mLlAdressMsg.setVisibility(View.GONE);
            mLlGlassMsg.setVisibility(View.GONE);
            mBtnLeft.setVisibility(View.GONE);
            mBtnRight.setText(R.string.edit_now);
        } else if (data.getStatus() == 2) {
            mllBottomBtn.setVisibility(View.GONE);
        } else if (data.getStatus() == 3) {
            mLookLog.setVisibility(View.VISIBLE);
            mBtnLeft.setVisibility(View.GONE);
            mBtnRight.setText(R.string.confirm_goods);
            rlLookLog.setOnClickListener(this);
        } else if (data.getStatus() == 4) {
            mBtnRight.setVisibility(View.GONE);
        } else if (data.getStatus() == 5) {
            mllBottomBtn.setVisibility(View.GONE);
        } else {
            mllBottomBtn.setVisibility(View.GONE);
        }
        mOrderNum.setText(getResources().getString(R.string.order_num) + data.getOrderNo());
        mOrderTime.setText(getResources().getString(R.string.order_time) +
                Util.changeStringDataStyle(data.getCreateTime()));
        String cover = data.getProduct().getImgList().get(0).getPath();
        ImageUtil.glideloadImage(CEApp.getResLink(cover), mIvGoods, R.drawable.ic_text);
        String title = data.getProduct().getTitle();
        mTvItemtitle.setText(title);
        String price = data.getPrice();
        mTvGoodsPrice.setText(price);
        String colorName = null;
        String colorCode = data.getColorCode();
        List<OrderListModel.ProductBean.ColorListBean> colorList = data.getProduct().getColorList();
        for (int i = 0; i < colorList.size(); i++) {
            if (colorList.get(i).getCode().equals(colorCode)) {
                colorName = colorList.get(i).getName();
            }
        }
        if (colorName != null) {
            mTvGoodsParam.setText(getResources().getString(R.string.glass_color) + colorName);
        }
        String glassName = null;
        int id = data.getRefractiveId();
        List<OrderListModel.ProductBean.RefractiveListBean> refractiveList = data.getProduct().getRefractiveList();
        for (int i = 0; i < refractiveList.size(); i++) {
            if (refractiveList.get(i).getId() == id) {
                glassName = refractiveList.get(i).getTitle();
            }
        }
        if (glassName != null) {
            mTvGoodsParam1.setText(getResources().getString(R.string.glasses) + glassName);
        }
        if (data.getStatus() != 1) {
            addressId = data.getAddressId();
            adressImpl.listAdress();
            if (!TextUtils.isEmpty(data.getRemark())) {
                mRlLeaveMsg.setVisibility(View.VISIBLE);
                mLeaveMsg.setText(data.getRemark());
            }
            adapter.setHealthData(data.getEyeData());
            mOptometryDate.setText(Util.changeStringDataStyle(data.getEyeData().getDataTime()));
            mDataCome.setText(data.getEyeData().getFrom());
            mGlassName.setText(data.getGlassMan().getRealName());
        }
    }


    @Override
    public void adressListSuccess(List<MyAdressModel> model) {
        for (int i = 0; i < model.size(); i++) {
            if (model.get(i).getId() == addressId) {
                setAdressData(model.get(i));
            }
        }
    }

    private void setAdressData(MyAdressModel model) {
        mTvAdressName.setText(model.getName());
        mTvAdressPhone.setText(model.getPhone1());
        mTvAdressDetail.setText(model.getAddress());
    }

    @Override
    public void adressListFail() {

    }

    @Override
    public void deleteAdressSuccess(List<MyAdressModel> model) {

    }

    @Override
    public void deleteAdressFail() {

    }

    @Override
    public void setDefaultAdressSuccess(List<MyAdressModel> model) {

    }

    @Override
    public void setDefaultAdressFail() {

    }

    @Override
    public void addAdressSuccess() {

    }

    @Override
    public void addAdressFail() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == WAN_SHAN && resultCode == 202) {
            finish();
        }
        if (requestCode == QUIT_RENT && resultCode == 202) {
            finish();
        }
    }
}
